<template>
  <div class="user-management-container">
    <!-- 页面标题 -->
<!--    <div class="page-title">用户管理</div>-->

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
              v-model="searchForm.username"
              placeholder="请输入登录用户名"
              clearable
          ></el-input>
        </el-col>
        <el-col :span="6">
          <el-input
              v-model="searchForm.realName"
              placeholder="请输入真实姓名"
              clearable
          ></el-input>
        </el-col>
        <el-col :span="6">
          <el-input
              v-model="searchForm.phone"
              placeholder="请输入手机号"
              clearable
          ></el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetForm" style="margin-left: 10px;">重置</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 卡片列表区域 -->
    <div class="card-list">
      <el-skeleton :loading="loading" row="6" :columns="3" animated>
        <el-card
            class="user-card"
            v-for="(user, index) in tableData"
            :key="user.id || index"
        >
          <!-- 卡片头部：头像和基本信息 -->
          <div class="card-header">
            <el-image
                :src=   "`/api/file/download.do?filename=${user.avatarUrl}`"
                :alt="user.realName || user.username"
                class="user-avatar"
                fallback-src="https://cube.elemecdn.com/9/c2/f0ee8a3c7c7c8a25685991b27286jpeg.jpeg"
            ></el-image>

            <div class="header-info">
              <div class="user-name">
                {{ user.realName || user.username || '--' }}
                <el-tag
                    :type="user.status === 1 ? 'success' : 'danger'"
                >
                  {{ user.status === 1 ? '正常' : '禁用' }}
                </el-tag>
              </div>
              <div class="user-id">用户ID: {{ user.id || '--' }}</div>
            </div>
          </div>

          <!-- 卡片主体：详细信息 -->
          <div class="card-body">
            <div class="info-group">
              <div class="info-item">
                <span class="label">登录账号:</span>
                <span class="value">{{ user.username || '--' }}</span>
              </div>
              <div class="info-item">
                <span class="label">手机号:</span>
                <span class="value">{{ user.phone || '--' }}</span>
              </div>
              <div class="info-item full-width">
                <span class="label">身份证:</span>
                <span class="value">
                  {{ user.idCardEncrypted ? '已认证' : '未认证' }}
                </span>
              </div>
              <div class="info-item full-width">
                <span class="label">驾驶证:</span>
                <span class="value">
                  {{ user.driverLicenseEncrypted ? '已认证' : '未认证' }}
                </span>
              </div>
            </div>
          </div>

          <!-- 卡片操作区 -->
          <div class="card-actions">
            <el-button
                size="small"
                type="primary"
                @click="handleDetail(user)"
                :disabled="!user.id"
            >
              详情
            </el-button>
            <el-button
                size="small"
                :type="user.status === 1 ? 'danger' : 'success'"
                @click="user.status === 1 ? handleForbid(user.id) : handleActivate(user.id)"
                :disabled="!user.id"
            >
              {{ user.status === 1 ? '禁用' : '激活' }}
            </el-button>
            <el-button
                size="small"
                type="warning"
                @click="handleDelete(user.id)"
                :disabled="!user.id"
                style="margin-left: 5px;"
            >
              删除
            </el-button>
          </div>
        </el-card>
      </el-skeleton>
    </div>

    <!-- 空状态提示 -->
    <div v-if="!loading && tableData.length === 0" class="empty-state">
      <el-empty description="暂无用户数据"></el-empty>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNo"
          :page-sizes="[6, 12, 24, 48]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
    </div>

    <!-- 详情模态框（改为纵向排列） -->
    <el-dialog
        title="用户详情"
        v-model="detailDialogVisible"
        width="50%"
        :close-on-click-modal="false"
    >
      <div class="detail-content">
        <!-- 头像区域 -->
        <div class="avatar-section">
          <el-image
              :src=   "`/api/file/download.do?filename=${currentUser?.avatarUrl}`"
              :alt="currentUser?.realName || currentUser?.username"
              class="detail-avatar"
              fallback-src="https://cube.elemecdn.com/9/c2/f0ee8a3c7c7c8a25685991b27286jpeg.jpeg"
          ></el-image>
          <div class="avatar-info">
            <div class="detail-name">
              {{ currentUser?.realName || currentUser?.username || '--' }}
              <el-tag
                  :type="currentUser?.status === 1 ? 'success' : 'danger'"
                  class="status-tag"
              >
                {{ currentUser?.status === 1 ? '正常' : '禁用' }}
              </el-tag>
            </div>
            <div class="detail-id">用户ID: {{ currentUser?.id || '--' }}</div>
          </div>
        </div>

        <!-- 详细信息（纵向排列） -->
        <el-descriptions column="1" border class="detail-descriptions">
          <el-descriptions-item label="登录用户名">
            {{ currentUser?.username || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="密码">
            {{ currentUser?.password || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="真实姓名">
            {{ currentUser?.realName || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号码">
            {{ currentUser?.phone || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="账号状态">
            <el-tag
                :type="currentUser?.status === 1 ? 'success' : 'danger'"
            >
              {{ currentUser?.status === 1 ? '正常使用中' : '已禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="身份证号">
            <template v-if="currentUser?.idCardEncrypted">
              <el-tooltip content="显示加密存储的身份证号" placement="top">
                <div class="encrypted-info">{{ currentUser?.idCardEncrypted || '--' }}</div>
              </el-tooltip>
            </template>
            <template v-else>未认证</template>
          </el-descriptions-item>
          <el-descriptions-item label="驾驶证号">
            <template v-if="currentUser?.driverLicenseEncrypted">
              <el-tooltip content="显示加密存储的驾驶证号" placement="top">
                <div class="encrypted-info">{{ currentUser?.driverLicenseEncrypted || '--' }}</div>
              </el-tooltip>
            </template>
            <template v-else>未认证</template>
          </el-descriptions-item>
          <el-descriptions-item label="身份证认证状态">
            <el-tag :type="currentUser?.idCardEncrypted ? 'success' : 'info'">
              {{ currentUser?.idCardEncrypted ? '已完成认证' : '未认证' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="驾驶证认证状态">
            <el-tag :type="currentUser?.driverLicenseEncrypted ? 'success' : 'info'">
              {{ currentUser?.driverLicenseEncrypted ? '已完成认证' : '未认证' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElDialog, ElDescriptions, ElDescriptionsItem, ElImage, ElSkeleton, ElEmpty, ElTooltip, ElTag } from 'element-plus'
import axios from 'axios'
import {activeUser, forbidUser, getUserList} from "@/api/AdminUser";

// 搜索表单数据
const searchForm = ref({
  username: '',
  realName: '',
  phone: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const pageNo = ref(1)
const pageSize = ref(6)

// 详情模态框相关
const detailDialogVisible = ref(false)
const currentUser = ref(null)

// 页面加载时获取数据
onMounted(() => {
  fetchUsers()
})

// 获取用户列表
const fetchUsers = async () => {
  if (loading.value) return // 防止重复请求
  loading.value = true
  try {
    const response = await getUserList( {
      params: {
        pageNo: pageNo.value,
        pageSize: pageSize.value,
        username: searchForm.value.username , // 空值不传递
        realName: searchForm.value.realName ,
        phone: searchForm.value.phone
      }
    })

    if (response?.code === 200 && response.data) {
      tableData.value = response.data.records || []
      total.value = response.data.count || 0
    } else {
      ElMessage.error(response?.message || '获取用户列表失败')
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取用户列表错误:', error)
    ElMessage.error('网络错误，获取用户列表失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 查看详情
const handleDetail = (user) => {
  if (!user) return
  currentUser.value = { ...user }
  detailDialogVisible.value = true
}

// 禁用用户
const handleForbid = async (id) => {
  if (!id) {
    ElMessage.warning('用户ID不存在')
    return
  }
  try {
    await ElMessageBox.confirm(
        '确定要禁用该用户吗？禁用后用户将无法登录系统',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'danger'
        }
    )

    const response = await forbidUser({ params: { id } })
    if (response?.code === 200) {
      ElMessage.success('禁用成功')
      fetchUsers()
    } else {
      ElMessage.error(response?.message || '禁用失败')
    }
  } catch (error) {
    if (error.name !== 'Error') { // 排除取消操作
      console.error('禁用用户错误:', error)
      ElMessage.error('操作失败，请重试')
    }
  }
}

// 激活用户
const handleActivate = async (id) => {
  if (!id) {
    ElMessage.warning('用户ID不存在')
    return
  }
  try {
    await ElMessageBox.confirm(
        '确定要激活该用户吗？激活后用户可正常登录系统',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }
    )

    const response = await activeUser({ params: { id } })
    if (response?.code === 200) {
      ElMessage.success('激活成功')
      fetchUsers()
    } else {
      ElMessage.error(response?.message || '激活失败')
    }
  } catch (error) {
    if (error.name !== 'Error') {
      console.error('激活用户错误:', error)
      ElMessage.error('操作失败，请重试')
    }
  }
}

// 删除用户
const handleDelete = async (id) => {
  if (!id) {
    ElMessage.warning('用户ID不存在')
    return
  }
  try {
    await ElMessageBox.confirm(
        '确定要删除该用户吗？此操作不可恢复，会删除用户所有相关数据！',
        '危险操作',
        {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'error',
          distinguishCancelAndClose: true
        }
    )

    const response = await axios.get('/api/admin/user/delete.do', { params: { id } })
    if (response?.data?.code === 200) {
      ElMessage.success('删除成功')
      fetchUsers() // 刷新列表
    } else {
      ElMessage.error(response?.data?.message || '删除失败')
    }
  } catch (error) {
    if (error.name !== 'Error' && error !== 'close') {
      console.error('删除用户错误:', error)
      ElMessage.error('操作失败，请重试')
    }
  }
}

// 搜索
const handleSearch = () => {
  pageNo.value = 1
  fetchUsers()
}

// 重置
const resetForm = () => {
  searchForm.value = {
    username: '',
    realName: '',
    phone: ''
  }
  pageNo.value = 1
  fetchUsers()
}

// 分页大小改变
const handleSizeChange = (val) => {
  if (val !== pageSize.value) {
    pageSize.value = val
    pageNo.value = 1
    fetchUsers()
  }
}

// 页码改变
const handleCurrentChange = (val) => {
  if (val !== pageNo.value) {
    pageNo.value = val
    fetchUsers()
  }
}
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.search-card {
  background-color: #fff;
  padding: 15px;
  margin-bottom: 20px;
}

.card-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.user-card {
  transition: all 0.3s ease;
  overflow: hidden;
}

.user-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  align-items: center;
  padding: 15px 15px 10px;
  border-bottom: 1px dashed #f0f0f0;
}

.user-avatar {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 15px;
  border: 2px solid #f0f0f0;
}

.header-info {
  flex-grow: 1;
}

.user-name {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.user-id {
  font-size: 13px;
  color: #888;
}

.card-body {
  padding: 15px;
}

.info-group {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.label {
  color: #666;
  width: 90px;
  flex-shrink: 0;
}

.value {
  color: #333;
  word-break: break-all;
  flex-grow: 1;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  padding: 12px 15px;
  border-top: 1px dashed #f0f0f0;
  gap: 10px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.pagination-container {
  text-align: right;
  margin-top: 20px;
}

/* 详情模态框样式（纵向排列） */
.detail-content {
  padding: 10px 0;
}

.avatar-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.detail-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 20px;
  border: 3px solid #f0f0f0;
}

.avatar-info {
  flex-grow: 1;
}

.detail-name {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.status-tag {
  margin-left: 15px;
}

.detail-id {
  color: #888;
  font-size: 14px;
}

.detail-descriptions {
  margin-top: 15px;
}

.encrypted-info {
  color: #666;
  font-family: monospace;
  word-break: break-all;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .card-list {
    grid-template-columns: 1fr;
  }

  .info-group {
    grid-template-columns: 1fr;
  }

  .info-item {
    grid-column: 1 / -1;
  }

  .card-actions {
    justify-content: center;
  }

  .avatar-section {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .detail-avatar {
    margin-right: 0;
    margin-bottom: 15px;
  }
}
</style>